package com.woohua.demo.datastructure;

/***
 * @title Link
 * @description
 * @author baiji
 * @version 1.0.0
 * @create 2023/8/14 9:57
 **/
public class Link<T> {

    private class Node {
        private T node;

        private Node next;

        public Node(T node, Node next) {
            this.node = node;
            this.next = next;
        }

        public Node(T node) {
            this.node = node;
        }
    }

    private Node head;

    private Node tail;

    private int size;

    public Link(Node node) {
        this.head = node;
        size = 0;
    }

    public void insert(int index, T data) throws Exception {
        if (index < 0 || index > this.size) {
            throw new Exception("插入超出范围");
        } else {
            Node newNode = new Node(data);
            if (index == 0) {
                if (this.size > 0) {
                    Node temp = head;
                    newNode.next = temp;
                }
                head = newNode;
            } else if (index == this.size) {
                Node temp = tail;
                temp.next = newNode;
                this.tail = newNode;
            } else {
                // 插入中间元素
                Node preNode = get(index - 1);
                Node nextNode = preNode.next;
                newNode.next = nextNode;
                preNode.next = newNode;

            }
        }
    }

    private Node get(int index) {
        if (index < 0 || index > this.size) {
            return null;
        } else {
            Node temp = this.head;
            for (int i = 0; i < index; i++) {
                temp = temp.next;
            }
            return temp;
        }
    }
}
